<button>Go</button>

<script src="../dist/bundles/mediabunny.cjs"></script>
<script src="../packages/mp3-encoder/dist/bundles/mediabunny-mp3-encoder.js"></script>

<script type="module">
    function download(blob, filename) {
		const url = URL.createObjectURL(blob);
		const a = document.createElement('a');
		a.href = url;
		a.download = filename;
		a.click();
		URL.revokeObjectURL(url);
	}

	MediabunnyMp3Encoder.registerMp3Encoder();

    const button = document.querySelector('button');
    button.addEventListener('click', async () => {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
        const videoTrack = stream.getVideoTracks()[0];
        const audioTrack = stream.getAudioTracks()[0];

        const output = new Mediabunny.Output({
            target: new Mediabunny.BufferTarget(),
            format: new Mediabunny.Mp4OutputFormat(),
        });
        if (videoTrack) {
            const source = new Mediabunny.MediaStreamVideoTrackSource(videoTrack, {
                codec: 'avc',
                bitrate: Mediabunny.QUALITY_MEDIUM
            });

            source.errorPromise.catch((d) => console.log("Hello?????", d));

            output.addVideoTrack(source);
        }
        if (audioTrack) {
            const source = new Mediabunny.MediaStreamAudioTrackSource(audioTrack, {
                codec: 'mp3',
                bitrate: Mediabunny.QUALITY_MEDIUM
            });

            source.errorPromise.catch((d) => console.log("Hello!!???", d));

            output.addAudioTrack(source);
        }

        await output.start();

        await new Promise(resolve => setTimeout(resolve, 5000));

        await output.finalize();

        console.log(output.target.buffer);
        download(new Blob([output.target.buffer]), 'livetest' + output.format.fileExtension);

        videoTrack?.stop();
        audioTrack?.stop();
    });
</script>